<?php

namespace App\Exports\Flight;

use App\Services\Flight\FlightSearchService;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterSheet;

class SevenDynamicSplitExport implements FromCollection,WithEvents
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        //

        $data[] = [
            '日期',
            '航班号',
            '起飞',
            '到达',
        ];

        $dates = [];

        $flightDynamicService = new FlightSearchService();
        $whereIn = $flightDynamicService->searchFlightDynamic(request());

        $where = [];
        if (request()->start_at){
            $where[] = ['created_at','>=',substr(request()->start_at,0,10)];
        }

        $interface = resolve('App\Repositories\Contracts\FlightDynamicInterface');
        $dynamics = $interface->get($where,'*',[],'id','desc','flight_id',$whereIn);

        if ($dynamics->isNotEmpty()) {

            //处理日期
            foreach ($dynamics as $key=>$value) {

                $sevenDelayArray = json_decode($value['sevenDay_ontime'],true);
                foreach ($sevenDelayArray as $val) {

                    $sevenDataItem = explode('，', $val);

                    $dateStr = str_replace(['月','日'],['-',''],$sevenDataItem[0]);
                    if (!in_array($dateStr, $dates)) {

                        //转换日期为了排序
                        $dates[] = $dateStr;
                    }
                }
            }


            rsort($dates);

            //组装数据
            foreach ($dynamics as $key=>$value) {

                $item = [
                    $value->created_at->format('Y-m-d'),
                    $value['flight_code'],
                    $value['dep_code'],
                    $value['arr_code'],
                ];

                $sevenDelayArray = json_decode($value['sevenDay_ontime'],true);

                $lastChangeFlights = json_decode($value['lastChangeFlights'],true);

                foreach ($dates as $date){

                    //检测是否有该日期
                    $dateExist = false;

                    foreach ($sevenDelayArray as $kSeven=>$valSeven) {

                        $sevenDataItem = explode('，', $valSeven);

                        //转换日期
                        $dateStr = str_replace(['月','日'],['-',''],$sevenDataItem[0]);

                        if ($date == $dateStr) {

                            $dateExist = true;

                            if ($sevenDataItem[1] == '取消') {

                                $item[] = $sevenDataItem[1];
                            } else {

                                $delayMinute = $sevenDataItem[2];

                                //遍历是调时
                                foreach ($lastChangeFlights as $vLast) {

                                    $lastChangeFlightsItem = explode(',',$vLast);

                                    if ($dateStr == date('n-d',strtotime($lastChangeFlightsItem[0])) && $lastChangeFlightsItem[2] == 1) {

                                        $delayMinute =  $delayMinute.','.$lastChangeFlightsItem[2];
                                    }

                                }


                                $item[] = $delayMinute;
                            }

                            break;
                        }
                    }


                    if (!$dateExist) {
                        $item[] = '';
                    }
                }

                $data[] = $item;
            }

        }

        $data[0] = array_merge($data[0],$dates);
        return collect($data);

    }

    /**
     * 注册事件
     * @return array
     */
    public function registerEvents(): array
    {



        return [
            AfterSheet::class => function (AfterSheet $event) {

                $colsTitleOne = ['A', 'B', 'C', 'D', 'E', 'F'];

                $colsTitle = $colsTitleTow = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H','I', 'J', 'K', 'L','M', 'N', 'O', 'P','Q','R','S','T','U','V','W','X','Y','Z'];

                foreach ($colsTitleOne as $colsOneV){
                    foreach ($colsTitleTow as $colsTwoV){

                        $colsTitle[] = $colsOneV.$colsTwoV;
                    }
                }


                $highestColumn = $event->getDelegate()->getHighestColumn();
                $highestRow = $event->getDelegate()->getHighestRow();

                $cols = [''];

                while (true) {

                    //每次变化都是新的一轮
                    $colsIndex = $cols;
                    foreach ($colsTitle as $title) {

                        foreach ($colsIndex as $col) {

                            $colStr = $col.$title;

                            for ($rowIndex = 1; $rowIndex <= $highestRow; $rowIndex++) {

                                $comment = $event->getSheet()->getDelegate()->getCell( $colStr.$rowIndex)->getValue();

                                if (strpos($comment,',')) {

                                    $commentArray = explode(',',$comment);
                                    $event->getSheet()->getDelegate()->getCell($colStr.$rowIndex)->setValue($commentArray[0]);

                                    //设置作者
                                    $event->sheet->getDelegate()->getStyle($colStr.$rowIndex)->applyFromArray([
                                        'font' => [
                                            'name' => 'Arial',
                                            'bold' => true,
                                            'italic' => false,
                                            'strikethrough' => false,
                                            'color' => [
                                                'rgb' => 'FF0000'
                                            ]
                                        ],
                                    ]);
                                }
                            }
                            $cols[] = $colStr;

                            if ($col.$title == $highestColumn) {

                                return;
                            }
                        }
                    }

                    if (count($cols) == 1) {

                        $cols = array_filter($cols);
                    }
                }

        }];

    }
}
